<?php
defined('IN_MAIN') or exit('Invalid Access!');

function calc_unilevel($in_date){
/*
This function calculate the unilevel bonus for all the sales that is of second sale and onwards for a member (first sale of a member the
commission is calculated using different calculation methods). It will credit to the upline of the purchase owner up to 7 levels, according
to the qualification of an upline in the unilevel. Sales will also include maintenance volume from previous week.
*/

	//globalize access to unilevel, min_maintain
	global $vars;
	$db=$vars["db"];
	$unilevel = $vars['unilevel'];
	$min_maintain = $vars['min_maintain'];
	$maintenance_percent = $vars['maintenance_percent'];
	//calc_date = get the start and end of the input in_date
	$calc_date = get_week_start_end($in_date, 'Y-m-d H:i:s');
	$year = date("Y", strtotime($calc_date['start']));
	$month = date("n", strtotime($calc_date['start']));
	$week = date("W", strtotime($calc_date['end']));
	$maintain_time = strtotime($calc_date['end']) + (7 * 86400);
	$maintain_year = date("Y", $maintain_time);
	$maintain_month = date("n", $maintain_time);
	$maintain_week = date("W", $maintain_time);
	//max_level = get the maximum level of unilevel (7)
	$max_level = count($unilevel);
	
	//sales = get all the sales that is confirmed and is not first sale of a member within the date of input in_date
	$t = @mysql_num_rows($r=mysql_query("select * from $db->purchase where first_sale!='y' and status='confirmed' and cdate>='$calc_date[start]' and cdate<='$calc_date[end]'"));
	//foreach sales
	for($i=0;$i<$t;$i++){
		$sale = mysql_fetch_assoc($r);
		//uid = sale[uid]
		$uid = $sale['uid'];
		//if not isset upline_tree[uid]
		if (!isset($upline_tree[$uid])){
			//downline_id = uid
			//level = 1
			$downline_id = $uid;
			$level = 1;
			do{
				//if not isset users[downline_id]
				if (!isset($users[$downline_id])){
					//users[downline_id] = get short detail for user id = downline_id
					$users[$downline_id] = get_user_short_detail_by_id($downline_id);
				}
				//upline_id = get the upline id of downline_id
				$upline_id = $users[$downline_id]['matrix_upline'];
				//if upline_id
				if ($upline_id){
					$upline_tree[$uid][$level]['id'] = $upline_id;
					$upline_tree[$uid][$level]['volume'] = calc_personal_sales($upline_id, $calc_date['start'], $calc_date['end']);
					$upline_tree[$uid][$level]['downline'] = @mysql_result(mysql_query("select count(*) from $db->users where matrix_upline='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
					$level += 1;
					$downline_id = $upline_id;
				}
			}while ($upline_id && $level <= $max_level);
		}
		
		//if exist upline_tree[uid]
		if (is_array($upline_tree[$uid])){
			//foreach upline_tree[uid] as level
			for($j = 1,$t2=count($upline_tree[$uid]);$j<$t2;$j++){
				$level = $j;
				//upline_id = upline_tree[uid][level][id]
				$upline_id = $upline_tree[$uid][$level]['id'];
				//if upline_tree[uid][level][volume] >= min_maintain and upline_tree[uid][level][downline] >= unilevel[level][downline]
				if ($upline_tree[$uid][$level]['volume'] >= $min_maintain && $upline_tree[$uid][$level]['downline'] >= $unilevel[$level]['downline']){
					//comm_percent = unilevel[level][percent]
					//comm_amount = comm_percent * sale[amount]
					$comm_percent = $unilevel[$level]['percent'];
					$comm_amount = round($comm_percent * $sale['total_bv'] / 100, 2);
					//insert the commission into the member_comm table with type = unilevel, uid = upline_id, amount = comm_amount, percent = comm_percent, year, month, datetime
					$sql="insert into $db->member_comm (uid, from_uid, type, cid, amount, level, percent, year, month, week, status, cdate) values ('$upline_id', '$uid', 'u', '$sale[id]', '$comm_amount', '$level', '$comm_percent', '$year', '$month', '$week', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
					//if insert fail
						//record the error in the variable insert_error
					$insert_comm_detail="UID: $upline_id Sale ID: $sale[id] Amount: $comm_amount Level: $level Percent: $comm_percent%<br />\n";
					if(!mysql_query($sql)){
						$insert_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}else{
						$insert_success.=$insert_comm_detail;
					}
					//member_comm[upline_id] += comm_amount
					$member_comm[$upline_id] += $comm_amount;
				}
			}
		}
	}
	
	//maintain = get all the maintenance that is within the date of input in_date
	$t = @mysql_num_rows($r=mysql_query("select * from $db->member_maintain where year='$year' and week='$week'"));
	//foreach sales
	for($i=0;$i<$t;$i++){
		$maintain = mysql_fetch_assoc($r);
		//uid = maintain[uid]
		$uid = $maintain['uid'];
		//if not isset upline_tree[uid]
		if (!isset($upline_tree[$uid])){
			//downline_id = uid
			//level = 1
			$downline_id = $uid;
			$level = 1;
			do{
				//if not isset users[downline_id]
				if (!isset($users[$downline_id])){
					//users[downline_id] = get short detail for user id = downline_id
					$users[$downline_id] = get_user_short_detail_by_id($downline_id);
				}
				//upline_id = get the upline id of downline_id
				$upline_id = $users[$downline_id]['matrix_upline'];
				//if upline_id
				if ($upline_id){
					$upline_tree[$uid][$level]['id'] = $upline_id;
					$upline_tree[$uid][$level]['volume'] = calc_personal_sales($upline_id, $calc_date['start'], $calc_date['end']);
					$upline_tree[$uid][$level]['downline'] = @mysql_result(mysql_query("select count(*) from $db->users where matrix_upline='$upline_id' and cdate<='$calc_date[end]'"), 0) or 0;
					$level += 1;
					$downline_id = $upline_id;
				}
			}while ($upline_id && $level <= $max_level);
		}
		
		//if exist upline_tree[uid]
		if (is_array($upline_tree[$uid])){
			//foreach upline_tree[uid] as level
			for($j = 1,$t2=count($upline_tree[$uid]);$j<$t2;$j++){
				$level = $j;
				//upline_id = upline_tree[uid][level][id]
				$upline_id = $upline_tree[$uid][$level]['id'];
				//if upline_tree[uid][level][volume] >= min_maintain and upline_tree[uid][level][downline] >= unilevel[level][downline]
				if ($upline_tree[$uid][$level]['volume'] >= $min_maintain && $upline_tree[$uid][$level]['downline'] >= $unilevel[$level]['downline']){
					//comm_percent = unilevel[level][percent]
					//comm_amount = comm_percent * maintain[amount]
					$comm_percent = $unilevel[$level]['percent'];
					$comm_amount = round($comm_percent * $maintain['amount'] / 100, 2);
					//insert the commission into the member_comm table with type = unilevel, uid = upline_id, amount = comm_amount, percent = comm_percent, year, month, datetime
					$sql="insert into $db->member_comm (uid, from_uid, type, nid, amount, level, percent, year, month, week, status, cdate) values ('$upline_id', '$uid', 'u', '$maintain[id]', '$comm_amount', '$level', '$comm_percent', '$year', '$month', '$week', 'confirmed', '".ndate('Y-m-d H:i:s')."')";
					//if insert fail
						//record the error in the variable insert_error
					$insert_comm_detail="UID: $upline_id Maintain ID: $maintain[id] Amount: $comm_amount Level: $level Percent: $comm_percent%<br />\n";
					if(!mysql_query($sql)){
						$insert_error.=$insert_comm_detail."SQL: $sql<br />\n";
					}else{
						$insert_success.=$insert_comm_detail;
					}
					//member_comm[upline_id] += comm_amount
					$member_comm[$upline_id] += $comm_amount;
				}
			}
		}
	}
	
	if ($member_comm){
		foreach ($member_comm as $uid => $amount){			
			$maintain_amount = round($amount * $maintenance_percent / 100, 2);
			//insert into member_maintain with uid = uid, type = plana, comm_type = sponsor bonus, percent = maintain[plana], amount = maintain_plana, pv = maintain_value_to_pv, date
			$sql = "insert into $db->member_maintain (uid, comm_type, percent, amount, year, month, week, cdate)
			values ('$uid', 'u', '$maintenance_percent', '$maintain_amount', '$maintain_year', '$maintain_month', '$maintain_week', '".ndate()."')";
			if(!mysql_query($sql)){
				$insert_main_err.="UID: $uid, comm code: u, percent: $maintenance_percent%, amount: $maintain_amount, year: $maintain_year, month: $maintain_month, week: $maintain_week\n";
			}
			
			$actual_amount = $amount - $maintain_amount;
			if(!mysql_query($sql="update $db->users set ewallet=ewallet+$actual_amount where id='$uid' limit 1")){
				$update_ew_err.="UID: $uid, amount: $actual_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$amount', '".addslashes("Credited $vars[currency]".number_format($amount, 2)." from bulk unilevel commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}
			
			//insert ewallet record for maintenance
			if(!mysql_query($sql="insert into $db->member_ewallet_record (uid, type, amount, descr, cdate) values ('$uid', 'debit', '$maintain_amount', '".addslashes("Debited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk unilevel commission received.")."', '".ndate()."')")){
				$insert_ewrec_err.=$sql."\n";
			}
			
			//update member swallet = swallet + maintain_amount
			if(!mysql_query($sql="update $db->users set swallet=swallet+$maintain_amount where id='$uid' limit 1")){
				$update_sw_err.="UID: $uid, amount: $maintain_amount\n";
			}elseif(!mysql_query($sql="insert into $db->member_swallet_record (uid, type, amount, descr, cdate) values ('$uid', 'credit', '$maintain_amount', '".addslashes("Credited $vars[currency]".number_format($maintain_amount, 2)." for maintenance from bulk unilevel commission received.")."', '".ndate()."')")){
				$insert_swrec_err.=$sql."\n";
			}
		}
	}
	
	if($insert_error || $insert_main_err){
		$status = false;
	}else{
		$status = true;
	}
	
	$errmsg = ($insert_error? "Failed Unilevel Commission Calculation:<br />\n<br />\n$insert_error" : "").
	($update_ew_err? "\nError crediting $vars[ewallet_title]:\n\n$update_ew_err" : "").
	($insert_ewrec_err? "\nError crediting $vars[ewallet_title] transactin record:\n\n$insert_ewrec_err" : "").
	($update_sw_err? "\nError crediting $vars[swallet_title]:\n\n$update_sw_err" : "").
	($insert_swrec_err? "\nError crediting $vars[swallet_title] transactin record:\n\n$insert_swrec_err" : "");
	
	return array('status'=>$status, 'errmsg'=>$errmsg);
}
?>